package com.jshan.blog.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jshan.blog.annotation.OperationLog;
import com.jshan.blog.base.admin.dto.MenuListDto;
import com.jshan.blog.base.admin.entity.SysMenu;
import com.jshan.blog.constans.RedisAllKeyConst;
import com.jshan.blog.enums.BizCodeEnums;
import com.jshan.blog.result.Result;
import com.jshan.blog.service.SysMenuService;
import com.jshan.blog.utils.RedisUtil;
import com.jshan.blog.valid.AddGroupValid;
import com.jshan.blog.valid.UpdateGroupValid;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/menu")
@Slf4j
@Tag(name = "菜单操作列表")
public class MenuController {

    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private RedisUtil redisUtil;


    @OperationLog(value = "根据type类型获取菜单数据", operationType = "查询")
    @Operation(summary = "根据type类型获取菜单数据", description = "传递的类型，one为只查找当前用户启用的menu， all则是所有menu")
    @GetMapping("/getMenuList/{type}")
    public Result getMenuList(@PathVariable("type") String type) {
        try {
            List<MenuListDto> menuListDto = sysMenuService.findMenuAll(type);
            return Result.ok(menuListDto);
        } catch (Exception e) {
            log.error("获取菜单失败，失败信息:{}", e.getMessage());
            return Result.fail(BizCodeEnums.FAILE.getCode(), "获取菜单失败");
        }
    }

    @OperationLog(value = "更新菜单数据", operationType = "更新")
    @Operation(summary = "更新菜单数据")
    @SaCheckPermission(value = {"sys:menu:edit"})
    @PostMapping("/updateMenu")
    public Result updateMenu(@Validated(value = {UpdateGroupValid.class}) @RequestBody MenuListDto menuListDto) {
        try {
            sysMenuService.updateMenuInfo(menuListDto);
            return Result.ok(BizCodeEnums.SUCCESS.getCode(), "菜单修改成功");
        } catch (Exception e) {
            log.error("更新菜单失败:{}", e.getMessage());
            return Result.fail(BizCodeEnums.FAILE.getCode(), "更新菜单失败");
        }

    }

    /**
     * 删除菜单
     *
     * @param id        菜单id
     * @param currentId 当前菜单id
     * @return Result
     */
    @OperationLog(value = "删除菜单", operationType = "删除")
    @SaCheckPermission(value = {"sys:menu:del"})
    @DeleteMapping("/deleteMenu/{id}/{currentId}")
    public Result deleteMenu(@PathVariable("id") Integer id, @PathVariable("currentId") Integer currentId) {
        if (id.intValue() == currentId.intValue()) {
            return Result.fail(BizCodeEnums.FAILE.getCode(), "不能删除当前所在的菜单");
        }
        SysMenu homeInfo = sysMenuService.getOne(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getName, "home"));
        if (ObjectUtils.isNotEmpty(homeInfo)) {
            if (id == homeInfo.getId().intValue()) {
                return Result.fail(BizCodeEnums.FAILE.getCode(), "首页菜单不能删除");
            }
        }
        List<SysMenu> one = sysMenuService.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPid, id));
        if (ObjectUtils.isEmpty(one)) {
            sysMenuService.removeById(id);
            // redisUtil.deleteAll(RedisAllKeyConst.ONE_MENU_KEY, RedisAllKeyConst.ALL_MENU_KEY);
            redisUtil.deleteValue(RedisAllKeyConst.ONE_MENU_KEY);
            redisUtil.deleteValue(RedisAllKeyConst.ALL_MENU_KEY);

            return Result.ok(BizCodeEnums.SUCCESS.getCode(), "删除成功！");
        }
        return Result.fail(BizCodeEnums.FAILE.getCode(), "请先删除子菜单");
    }

    @OperationLog(value = "获取父级菜单信息", operationType = "查询")
    @SaCheckPermission(value = {"sys:menu:manage"})
    @GetMapping("/getPartMenuList")
    public Result getPartMenuList() {
        List<Map<Integer, String>> partMenuList = sysMenuService.getPartMenuList();
        if (ObjectUtils.isNotEmpty(partMenuList)) {
            return Result.ok(partMenuList);
        }
        return Result.fail(BizCodeEnums.FAILE.getCode(), "获取父级菜单失败");

    }

    @OperationLog(value = "新增菜单", operationType = "新增")
    @SaCheckPermission(value = {"sys:menu:add"})
    @PostMapping("/addMenuInfo")
    public Result addMenuInfo(@Validated(value = {AddGroupValid.class}) @RequestBody MenuListDto menuListDto) {
        if (sysMenuService.saveMenuInfo(menuListDto)) {
            return Result.ok(BizCodeEnums.SUCCESS.getCode(), "添加菜单成功");
        }
        return Result.fail(BizCodeEnums.FAILE.getCode(), "添加菜单失败");
    }

    @OperationLog(value = "根据label查询菜单", operationType = "查询")
    @SaCheckPermission(value = {"sys:menu:manage"})
    @GetMapping("/getMenuInfo/{label}")
    public Result getMenuInfo(@PathVariable("label") String label) {
        SysMenu one = sysMenuService.getOne(new LambdaQueryWrapper<SysMenu>().like(SysMenu::getLabel, label));
        if (ObjectUtils.isNotEmpty(one)) {
            return Result.ok(one);
        }
        return Result.fail(BizCodeEnums.FAILE.getCode(), "没有查询的菜单！");
    }

    @OperationLog(value = "根据roleId查询菜单", operationType = "查询")
    @SaCheckPermission(value = {"sys:role:auth"})
    @GetMapping("/getMenuIds/{roleId}")
    public Result getMenuIds(@PathVariable("roleId") Integer roleId) {
        if (roleId != null) {
            List<Integer> ids = sysMenuService.getIds(roleId);
            return Result.ok(ids);
        }
        return Result.fail(BizCodeEnums.FAILE.getCode(), "获取菜单id列表失败");
    }
}
